package com.example.springboottest.example.elasticsearch;

import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * 默认认情况下端口 9300 用于传 输（ Tran port ）层，端口 9200 用于http
 */
public class ESApiTest {
    public static void main(String[] args) {
        TransportClient client = null;
        try {
//            Settings settings= Settings.builder().put("cluster.name","my-application").build();
            client = new PreBuiltTransportClient(Settings.EMPTY)
                    .addTransportAddress(new TransportAddress(InetAddress.getByName("127.0.0.1"), 9300));

//            TransportClient client2 = TransportClientFactory.getInstance().getClient();

//            client = TransportClient.builder().build().addTransportAddress(
//                    new InetSocketTransportAddress(InetAddress.getByName("localhost"), 9300));

            //获取数据
            GetResponse documentFields = client.prepareGet("library", "book", "4").get();
            System.out.println(documentFields.getIndex());
            System.out.println(documentFields.getType());
            System.out.println(documentFields.getId());
            System.out.println(documentFields.getSourceAsString());
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            client.close();
        }
    }
}
